package org.jeecg.modules.flowerAdjust.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.modules.DateUtils.GetDate;
import org.jeecg.modules.flower.entity.FlowerOutorder;
import org.jeecg.modules.flower.entity.TFlowerTagInMain2;
import org.jeecg.modules.flower.util.CommonUtil;
import org.jeecg.modules.flowerutil.controller.PeriodController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.flowerAdjust.entity.TFlowerAdjustTagIn;
import org.jeecg.modules.flowerAdjust.entity.TFlowerAdjustTagInMain;
import org.jeecg.modules.flowerAdjust.vo.TFlowerAdjustTagInMainPage;
import org.jeecg.modules.flowerAdjust.service.ITFlowerAdjustTagInMainService;
import org.jeecg.modules.flowerAdjust.service.ITFlowerAdjustTagInService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 批量入库调整主表
 * @Author: jeecg-boot
 * @Date:   2022-11-16
 * @Version: V1.0
 */
@Api(tags="批量入库调整主表")
@RestController
@RequestMapping("/flowerAdjust/tFlowerAdjustTagInMain")
@Slf4j
public class TFlowerAdjustTagInMainController {
	@Autowired
	private ITFlowerAdjustTagInMainService tFlowerAdjustTagInMainService;
	@Autowired
	private ITFlowerAdjustTagInService tFlowerAdjustTagInService;
	
	/**
	 * 分页列表查询
	 *
	 * @param tFlowerAdjustTagInMain
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "批量入库调整主表-分页列表查询")
	@ApiOperation(value="批量入库调整主表-分页列表查询", notes="批量入库调整主表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(TFlowerAdjustTagInMain tFlowerAdjustTagInMain,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   @RequestParam(value = "sDate", defaultValue = "") String sDate,
								   @RequestParam(value = "eDate", defaultValue = "") String eDate,
								   HttpServletRequest req) {
		//QueryWrapper<TFlowerAdjustTagInMain> queryWrapper = QueryGenerator.initQueryWrapper(tFlowerAdjustTagInMain, req.getParameterMap());
		LambdaQueryWrapper<TFlowerAdjustTagInMain> queryWrapper = new LambdaQueryWrapper<>();
		Page<TFlowerAdjustTagInMain> page = new Page<TFlowerAdjustTagInMain>(pageNo, pageSize);
		if (StringUtils.isNotBlank(tFlowerAdjustTagInMain.getAdjustNo())){
			queryWrapper.like(TFlowerAdjustTagInMain::getAdjustNo,tFlowerAdjustTagInMain.getAdjustNo());
		}
		if (StringUtils.isNotBlank(tFlowerAdjustTagInMain.getNo())){
			queryWrapper.like(TFlowerAdjustTagInMain::getNo,tFlowerAdjustTagInMain.getNo());
		}
		if (tFlowerAdjustTagInMain.getState()!=null){
			queryWrapper.like(TFlowerAdjustTagInMain::getState,tFlowerAdjustTagInMain.getState());
		}
		if (StringUtils.isNotBlank(sDate)){
			queryWrapper.ge(TFlowerAdjustTagInMain::getCreateTime,sDate);
		}
		if (StringUtils.isNotBlank(eDate)){
			queryWrapper.le(TFlowerAdjustTagInMain::getCreateTime,eDate + " 23:59:59");
		}
		queryWrapper.orderByDesc(TFlowerAdjustTagInMain::getAdjustNo);
		queryWrapper.orderByDesc(TFlowerAdjustTagInMain::getCreateTime);
		IPage<TFlowerAdjustTagInMain> pageList = tFlowerAdjustTagInMainService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 * 添加
	 *
	 * @param tFlowerAdjustTagInMainPage
	 * @return
	 */
	@AutoLog(value = "批量入库调整主表-添加")
	@ApiOperation(value="批量入库调整主表-添加", notes="批量入库调整主表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody TFlowerAdjustTagInMainPage tFlowerAdjustTagInMainPage) {
		TFlowerAdjustTagInMain tFlowerAdjustTagInMain = new TFlowerAdjustTagInMain();
		BeanUtils.copyProperties(tFlowerAdjustTagInMainPage, tFlowerAdjustTagInMain);
		//自动生成出库单号
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		String dateNo = simpleDateFormat.format(new Date());
		String refex = "RKTZ" + dateNo;
		LambdaQueryWrapper<TFlowerAdjustTagInMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.like(TFlowerAdjustTagInMain::getAdjustNo, refex);
		lambdaQueryWrapper.orderByDesc(TFlowerAdjustTagInMain::getAdjustNo);
		List<TFlowerAdjustTagInMain> list = tFlowerAdjustTagInMainService.list(lambdaQueryWrapper);
		String oldNo = "";
		if (list.size() > 0) {
			oldNo = list.get(0).getAdjustNo();
		}
		String no1 = CommonUtil.getNo("RKTZ", oldNo, 3);
		tFlowerAdjustTagInMain.setAdjustNo(no1);//自动生成出库单号
		tFlowerAdjustTagInMain.setState(0);
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		tFlowerAdjustTagInMain.setCreateBy(sysUser.getUsername());
		//自动生成出库单号========end====
		tFlowerAdjustTagInMainService.saveMain(tFlowerAdjustTagInMain, tFlowerAdjustTagInMainPage.getTFlowerAdjustTagInList());
		return Result.OK("添加成功!");
	}
	
	/**
	 * 编辑
	 *
	 * @param tFlowerAdjustTagInMainPage
	 * @return
	 */
	@AutoLog(value = "批量入库调整主表-编辑")
	@ApiOperation(value="批量入库调整主表-编辑", notes="批量入库调整主表-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<?> edit(@RequestBody TFlowerAdjustTagInMainPage tFlowerAdjustTagInMainPage) {
		TFlowerAdjustTagInMain tFlowerAdjustTagInMain = new TFlowerAdjustTagInMain();
		BeanUtils.copyProperties(tFlowerAdjustTagInMainPage, tFlowerAdjustTagInMain);
		tFlowerAdjustTagInMainService.updateMain(tFlowerAdjustTagInMain, tFlowerAdjustTagInMainPage.getTFlowerAdjustTagInList());
		return Result.OK("编辑成功!");
	}

	 /**
	  *财务审核
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "批量入库调整主表-财务审核")
	 @ApiOperation(value="批量入库调整主表-财务审核", notes="批量入库调整主表-财务审核")
	 @GetMapping(value = "/financeSure")
	 public Result<?> financeSure(@RequestParam(value = "id") String id) throws IOException{
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		 TFlowerAdjustTagInMain adjustTagInMain = tFlowerAdjustTagInMainService.getById(id);
		 if (adjustTagInMain.getState()==1){
			 throw new RuntimeException("您已经成功财务审核过了！");
		 }
		 if (adjustTagInMain.getState()!=0){
			 throw new RuntimeException("只有草稿状态才能进行财务审核");
		 }
		 LambdaUpdateWrapper<TFlowerAdjustTagInMain> updateWrapper = new LambdaUpdateWrapper<>();
		 updateWrapper.eq(TFlowerAdjustTagInMain::getId,id);
		 updateWrapper.set(TFlowerAdjustTagInMain::getState,1);
		 updateWrapper.set(TFlowerAdjustTagInMain::getFinanceSureUser,sysUser.getUsername());
		 updateWrapper.set(TFlowerAdjustTagInMain::getFinanceSureTime, GetDate.getCurrentDateAndTime());
		 boolean update = tFlowerAdjustTagInMainService.update(null, updateWrapper);
		 return Result.OK("财务审核成功!");
	 }

	 /**
	  *撤销财务审核
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "批量入库调整主表-撤销财务审核")
	 @ApiOperation(value="批量入库调整主表-撤销财务审核", notes="批量入库调整主表-撤销财务审核")
	 @GetMapping(value = "/financeCancelSure")
	 public Result<?> financeCancelSure(@RequestParam(value = "id") String id) throws IOException{
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		 TFlowerAdjustTagInMain adjustTagInMain = tFlowerAdjustTagInMainService.getById(id);
		 if (adjustTagInMain.getState()==0){
			 throw new RuntimeException("您已经成功撤销财务审核过了！");
		 }
		 if (adjustTagInMain.getState()!=1){
			 throw new RuntimeException("只有财务审核状态才能进行撤销财务审核");
		 }
		 LambdaUpdateWrapper<TFlowerAdjustTagInMain> updateWrapper = new LambdaUpdateWrapper<>();
		 updateWrapper.eq(TFlowerAdjustTagInMain::getId,id);
		 updateWrapper.set(TFlowerAdjustTagInMain::getState,0);
		 updateWrapper.set(TFlowerAdjustTagInMain::getFinanceSureUser,sysUser.getUsername());
		 updateWrapper.set(TFlowerAdjustTagInMain::getFinanceSureTime, GetDate.getCurrentDateAndTime());
		 boolean update = tFlowerAdjustTagInMainService.update(null, updateWrapper);
		 return Result.OK("撤销财务审核成功!");
	 }

	 /**
	  *库管审核
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "批量入库调整主表-库管审核")
	 @ApiOperation(value="批量入库调整主表-库管审核", notes="批量入库调整主表-库管审核")
	 @GetMapping(value = "/storeSure")
	 public Result<?> storeSure(@RequestParam(value = "id") String id) throws IOException{
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		 TFlowerAdjustTagInMain adjustTagInMain = tFlowerAdjustTagInMainService.getById(id);
		 if (adjustTagInMain.getState()==2){
			 throw new RuntimeException("您已经成功库管审核过了！");
		 }
		 if (adjustTagInMain.getState()!=1){
			 throw new RuntimeException("只有财务审核状态才能进行库管审核");
		 }
		 LambdaUpdateWrapper<TFlowerAdjustTagInMain> updateWrapper = new LambdaUpdateWrapper<>();
		 updateWrapper.eq(TFlowerAdjustTagInMain::getId,id);
		 updateWrapper.set(TFlowerAdjustTagInMain::getState,2);
		 updateWrapper.set(TFlowerAdjustTagInMain::getStorekeeperSureUser,sysUser.getUsername());
		 updateWrapper.set(TFlowerAdjustTagInMain::getStorekeeperSureTime, GetDate.getCurrentDateAndTime());
		 boolean update = tFlowerAdjustTagInMainService.update(null, updateWrapper);
		 return Result.OK("库管审核成功!");
	 }

	 /**
	  *撤销库管审核
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "批量入库调整主表-撤销库管审核")
	 @ApiOperation(value="批量入库调整主表-撤销库管审核", notes="批量入库调整主表-撤销库管审核")
	 @GetMapping(value = "/storeCancelSure")
	 public Result<?> storeCancelSure(@RequestParam(value = "id") String id) throws IOException{
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		 TFlowerAdjustTagInMain adjustTagInMain = tFlowerAdjustTagInMainService.getById(id);
		 if (adjustTagInMain.getState()==1){
			 throw new RuntimeException("您已经成功撤销库管审核过了！");
		 }
		 if (adjustTagInMain.getState()!=2){
			 throw new RuntimeException("只有库管审核状态才能进行撤销库管审核");
		 }
		 LambdaUpdateWrapper<TFlowerAdjustTagInMain> updateWrapper = new LambdaUpdateWrapper<>();
		 updateWrapper.eq(TFlowerAdjustTagInMain::getId,id);
		 updateWrapper.set(TFlowerAdjustTagInMain::getState,1);
		 updateWrapper.set(TFlowerAdjustTagInMain::getStorekeeperSureUser,sysUser.getUsername());
		 updateWrapper.set(TFlowerAdjustTagInMain::getStorekeeperSureTime, GetDate.getCurrentDateAndTime());
		 boolean update = tFlowerAdjustTagInMainService.update(null, updateWrapper);
		 return Result.OK("撤销库管审核成功!");
	 }

	 /**
	  *运管审核
	  *
	  * @param tFlowerAdjustTagInMainPage
	  * @return
	  */
	 @AutoLog(value = "批量入库调整主表-运管审核")
	 @ApiOperation(value="批量入库调整主表-运管审核", notes="批量入库调整主表-运管审核")
	 @RequestMapping(value = "/operationSure", method = {RequestMethod.PUT,RequestMethod.POST})
	 @Transactional
	 public Result<?> operationSure(@RequestBody TFlowerAdjustTagInMainPage tFlowerAdjustTagInMainPage) throws IOException{
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		 TFlowerAdjustTagInMain adjustTagInMain = tFlowerAdjustTagInMainService.getById(tFlowerAdjustTagInMainPage.getId());
		 if (adjustTagInMain.getState()==3){
			 throw new RuntimeException("您已经成功运管审核过了！");
		 }
		 if (adjustTagInMain.getState()!=2){
			 throw new RuntimeException("只有财务审核状态才能进行运管审核");
		 }
		 LambdaUpdateWrapper<TFlowerAdjustTagInMain> updateWrapper = new LambdaUpdateWrapper<>();
		 updateWrapper.eq(TFlowerAdjustTagInMain::getId,tFlowerAdjustTagInMainPage.getId());
		 updateWrapper.set(TFlowerAdjustTagInMain::getState,2);
		 updateWrapper.set(TFlowerAdjustTagInMain::getOperationSureUser,sysUser.getUsername());
		 updateWrapper.set(TFlowerAdjustTagInMain::getOperationSureTime, GetDate.getCurrentDateAndTime());
		 boolean update = tFlowerAdjustTagInMainService.update(null, updateWrapper);

		 List<TFlowerAdjustTagIn> tFlowerAdjustTagInList = tFlowerAdjustTagInMainPage.getTFlowerAdjustTagInList();
		 for (TFlowerAdjustTagIn tFlowerAdjustTagIn:tFlowerAdjustTagInList){
			 String varietyCode = tFlowerAdjustTagIn.getVarietyCode();
			 Integer tagNum = tFlowerAdjustTagIn.getTagNum();
			 int i = tFlowerAdjustTagInMainService.updateTagInfo(tagNum, varietyCode);
			 if (i==0){
				 throw new RuntimeException("在台账中未找到相应的商品");
			 }
		 }
		 return Result.OK("运管审核成功!");
	 }
	 
	 
	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "批量入库调整主表-通过id删除")
	@ApiOperation(value="批量入库调整主表-通过id删除", notes="批量入库调整主表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
	    tFlowerAdjustTagInMainService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "批量入库调整主表-批量删除")
	@ApiOperation(value="批量入库调整主表-批量删除", notes="批量入库调整主表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tFlowerAdjustTagInMainService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
     *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "批量入库调整主表-通过id查询")
	@ApiOperation(value="批量入库调整主表-通过id查询", notes="批量入库调整主表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		TFlowerAdjustTagInMain tFlowerAdjustTagInMain = tFlowerAdjustTagInMainService.getById(id);
		return Result.OK(tFlowerAdjustTagInMain);
	}
	
	/**
	 * 通过id查询
     *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "批量入库调整子表-通过主表ID查询")
	@ApiOperation(value="批量入库调整子表-通过主表ID查询", notes="批量入库调整主表-通过主表ID查询")
	@GetMapping(value = "/queryTFlowerAdjustTagInByMainId")
	public Result<?> queryTFlowerAdjustTagInListByMainId(@RequestParam(name="id",required=true) String id) {
		List<TFlowerAdjustTagIn> tFlowerAdjustTagInList = tFlowerAdjustTagInService.selectByMainId(id);
		return Result.OK(tFlowerAdjustTagInList);
	}

  /**
   * 导出excel
   *
   * @param request
   * @param tFlowerAdjustTagInMain
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, TFlowerAdjustTagInMain tFlowerAdjustTagInMain) {
      // Step.1 组装查询条件
      QueryWrapper<TFlowerAdjustTagInMain> queryWrapper = QueryGenerator.initQueryWrapper(tFlowerAdjustTagInMain, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<TFlowerAdjustTagInMainPage> pageList = new ArrayList<TFlowerAdjustTagInMainPage>();
      List<TFlowerAdjustTagInMain> tFlowerAdjustTagInMainList = tFlowerAdjustTagInMainService.list(queryWrapper);
      for (TFlowerAdjustTagInMain temp : tFlowerAdjustTagInMainList) {
          TFlowerAdjustTagInMainPage vo = new TFlowerAdjustTagInMainPage();
          BeanUtils.copyProperties(temp, vo);
          List<TFlowerAdjustTagIn> tFlowerAdjustTagInList = tFlowerAdjustTagInService.selectByMainId(temp.getId());
          vo.setTFlowerAdjustTagInList(tFlowerAdjustTagInList);
          pageList.add(vo);
      }
      //Step.3 调用AutoPoi导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "批量入库调整主表");
      mv.addObject(NormalExcelConstants.CLASS, TFlowerAdjustTagInMainPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("批量入库调整主表数据", "导出人:"+sysUser.getRealname(), "批量入库调整主表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<TFlowerAdjustTagInMainPage> list = ExcelImportUtil.importExcel(file.getInputStream(), TFlowerAdjustTagInMainPage.class, params);
              for (TFlowerAdjustTagInMainPage page : list) {
                  TFlowerAdjustTagInMain po = new TFlowerAdjustTagInMain();
                  BeanUtils.copyProperties(page, po);
                  tFlowerAdjustTagInMainService.saveMain(po, page.getTFlowerAdjustTagInList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
  }

}
